using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model.Core.DbContexts;
using Model.Core.Entity.District;
using RobotWebApiService.Models;
using RobotWebApiService.Models;

namespace RobotWebApiService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MapInfoController : ControllerBase
    {
        private readonly MyDbContext _context;

        public MapInfoController(MyDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public ApiResponse<IEnumerable<MapInfo>> Get()
        {
            try
            {
                return new ApiResponse<IEnumerable<MapInfo>>(true, "", _context.MapInfo.ToList());
            }
            catch (Exception ex)
            {
                return new ApiResponse<IEnumerable<MapInfo>>(false, ex.Message);
            }
        }

        [HttpPost]
        public ApiResponse<MapInfo> Post([FromBody] MapInfo entity)
        {
            try
            {
                if (!ModelState.IsValid)
                    return new ApiResponse<MapInfo>(false, "无效的请求数据");

                _context.MapInfo.Add(entity);
                _context.SaveChanges();
                return new ApiResponse<MapInfo>(true, "创建成功", entity);
            }
            catch (Exception ex)
            {
                return new ApiResponse<MapInfo>(false, ex.Message);
            }
        }

        [HttpPut("{id}")]
        public ApiResponse<MapInfo> Put(string id, [FromBody] MapInfo entity)
        {
            try
            {
                if (Guid.Parse(id) != entity.Id)
                    return new ApiResponse<MapInfo>(false, "ID不匹配");

                _context.Entry(entity).State = EntityState.Modified;
                _context.SaveChanges();
                return new ApiResponse<MapInfo>(true, "更新成功", entity);
            }
            catch (Exception ex)
            {
                return new ApiResponse<MapInfo>(false, ex.Message);
            }
        }

        [HttpDelete("{id}")]
        public ApiResponse<string> Delete(string id)
        {
            try
            {
                var entity = _context.MapInfo.Find(id);
                if (entity == null)
                    return new ApiResponse<string>(false, "未找到该记录");

                _context.MapInfo.Remove(entity);
                _context.SaveChanges();
                return new ApiResponse<string>(true, "删除成功");
            }
            catch (Exception ex)
            {
                return new ApiResponse<string>(false, ex.Message);
            }
        }
    }
}